File and Writing Java Object to File
File class is neither byte stream nor character stream. it represents a file or directory path and provides information about it (name, path, size, permissions, etc.).
We can use FileWriter object to write characters / text to a file. It is a Character stream.
| Java Class | Type | Purpose |
|---|---|---|
| File | Neither | Represents a file/directory |
| FileInputStream | Byte Stream | Reads raw bytes |
| FileOutputStream | Byte Stream | Writes raw bytes |
| FileReader | Character Stream | Reads Characters |
| FileWriter | Character Stream | Writes Characters |
We can write an actual Java object to a file and later reconstruct that object using
import java.io.*;
class Student implements Serializable {
int id;
String name;
Student(int id, String name) {
this.id = id;
this.name = name;
}
}
public class Main {
public static void main(String[] args) throws Exception {
Student s = new Student(101, "Ram");
// Write object
ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream("student.dat"));
out.writeObject(s);
out.close();
// Read object
ObjectInputStream in =
new ObjectInputStream(new FileInputStream("student.dat"));
Student s2 = (Student) in.readObject();
in.close();
System.out.println(s2.id);
System.out.println(s2.name);
}
}
We cannot use a character stream to read / write Java object to a file. FileWriter and FileReader are designed for characters/text, whereas, serialized Java object is represented as binary data.
Objects can be stored as text. We can convert an object's data into a text format, such as JSON, and then use character streams.